<?php
namespace backend\controllers;

use Yii;
use yii\web\Controller;
use yii\data\Pagination;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\helpers\Json;
use common\models\Product;
use backend\models\ProductForm;
use backend\models\ProductDataForm;
use yii\web\UploadedFile;
use yii\web\ForbiddenHttpException;

/**
 * Product controller
 */
class ProductController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['create', 'datalist'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    /*
    * 新建产品
     */
    public function actionCreate($id=null)
    {
        if(!Yii::$app->user->can('createProduct')){
            throw new ForbiddenHttpException('对不起，您现在还没获得此操作的权限');
        }

        $model = new ProductForm($id);
        if ($model->load(Yii::$app->request->post())) {
            $model->pro_img = UploadedFile::getInstance($model, 'pro_img');
            if ($model->validate()) {
                if ($model->addOrUpdate()) {

                    return $this->redirect(['product/datalist']);
                }
            }
        }

        return $this->render('create', ['model' => $model]);
    }

    /*
    * 产品列表
     */
    public function actionDatalist()
    {
        if(!Yii::$app->user->can('updateProduct')){
            throw new ForbiddenHttpException('对不起，您现在还没获得此操作的权限');
        }

        $data_form = new ProductDataForm;
        $data = Product::find();
        if ($data_form->load(Yii::$app->request->get()) && $data_form->validate()) {
            $data = $data_form->query();
        }

        $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => '10']);
        $model = $data->offset($pages->offset)->limit($pages->limit)->all();

        return $this->render('datalist', ['model' => $model, 'pages' => $pages]);
    }

}    